<?php

namespace App\Http\Controllers\Admin;

use App\Services\WxCardMemberLevel\WxCardMemberLevelService;
use App\Services\WxCard\WxCardService;
use Illuminate\Http\Request;

/**
 * 微信会员卡控制器
 * @package App\Http\Controllers\Admin
 */
class WxCardMemberLevelController extends BaseWxController
{
    /**
     * 构造函数
     */
    public function __construct()
    {
        parent::__construct();
    }
    /**
     * 菜单管理首页
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request, WxCardService $wxCardSer, WxCardMemberLevelService $memberLevelSer)
    {
        if ($request->ajax()){
            $cardBaseId = $request->get('cardBaseId', 0);
            $levelList = $memberLevelSer->getList($cardBaseId);
            foreach ($levelList as $k => $v){
                $v['text'] = $v['name'];
                $v['tags'] = [
                    '排序：'.$v['order_num'],
                    '等级标识:' . $memberLevelSer->getLevelKeyName($v['key']),
                    ];
                $v['nodes'] = [];
                $levelList[$k] = $v;
            }

            $data['levelList'] = array_values($levelList);
            return $data;
        }
        //卡券列表
        $this->viewData['memberCardList'] = $wxCardSer->getCardListByType(WxCardService::CARD_TYPE_MEMBER_CARD);
        //会员标识
        $this->viewData['levelKeyList'] = $memberLevelSer->getLevelKeyList();

        return view('admin.wxcardmemberlevel.index', $this->viewData);
    }

    /**
     * 保存、添加菜单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function save(\App\Http\Requests\AdminWxCardMemberLevelPost $request, WxCardMemberLevelService $memberLevelSer)
    {
        try {
            $rs = $memberLevelSer->save($request);
            if ($rs) {
                return $this->showMsg('success', ($request->input('id') ? '编辑' : '添加') . '会员等级成功', [], 'admin.wxcardmemberlevel.index');
            }
            throw new \Exception(($request->input('id') ? '编辑' : '添加') . '会员等级失败');
        } catch (\Exception $e) {
            return $this->showMsg('error', $e->getMessage());
        }
    }

    /**
     * 删除菜单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\Response
     */
    public function destroy(Request $request, WxCardMemberLevelService $memberLevelSer)
    {
        try {
            $id = $request->input('id', 0);
            if (!$id) {
                throw new \Exception('请指定要删除的菜单');
            }
            $rs = $memberLevelSer->del($id);
            if (!$rs) {
                throw new \Exception('删除会员等级失败');
            }
            return $this->showMsg('success', '删除会员等级成功');
        } catch (\Exception $e) {
            return $this->showMsg('error', $e->getMessage());
        }
    }
}
